from stw_app import models
from stw_app.models import UserInfo
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import urllib.parse
import urllib
import urllib.request
import json
from urllib.error import HTTPError, URLError
from datetime import datetime


@csrf_exempt
def check(request):
    if request.method == "POST":
        appCode = "18de84c31a734f0ea91f81d848c6d51d"
        url = "https://eid.shumaidata.com/eid/check"
        data = {
            "idcard": request.POST.get("ID_card"),
            "name": request.POST.get("name"),
        }
        print("data:", data)
        headers = {'Authorization': 'APPCODE ' + appCode}
        fdata = urllib.parse.urlencode(data).encode(encoding='UTF8')
        req = urllib.request.Request(url, headers=headers, data=fdata)
        try:
            response = urllib.request.urlopen(req)
            content = response.read()
            if content:
                content_str = content.decode('UTF-8')  # 将返回的字节流解码为字符串
                result = json.loads(content_str)  # 将JSON字符串解析为Python对象（字典）
                user = result['result']
                print('user:', user)
                return JsonResponse({'success': True, 'data': user})
        except HTTPError as e:
            print('HTTPError: ', e.reason, e.code, e.headers)
    return JsonResponse({'success': False})


@csrf_exempt
def register(request):
    if request.method == "POST":
        name = request.POST.get('name')
        ID_card = request.POST.get('ID_card')
        nick_name = request.POST.get('nick_name')
        phone = request.POST.get('phone')
        password = request.POST.get('password')
        gender = request.POST.get('gender')
        birthday = request.POST.get('birthday')
        # 计算年龄
        current_date = datetime.now()
        birthday = datetime.strptime(birthday, "%Y%m%d")
        age = current_date.year - birthday.year - \
              ((current_date.month, current_date.day) < (birthday.month, birthday.day))
        max_id = models.UserInfo.objects.order_by('-id').first()
        tmp_id = max_id.id + 1
        new_user = UserInfo(name=name, password=password, phone=phone, id_card=ID_card, nick_name=nick_name,
                            gender=gender, age=age, id=tmp_id)
        new_user.save()
        return JsonResponse({'success': True})
    else:
        return JsonResponse({'success': False})


# 登录注册
